import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.LinkedList;


public class UDPSocketControl64KBLimit extends DatagramSocket implements Runnable
{

	private boolean runListen = false;	
	private LinkedList<Object> reciveData = new LinkedList<Object>();
	private InetSocketAddress socketAddress = null;


	public UDPSocketControl64KBLimit(int port) throws SocketException 
	{
		super(port);
		socketAddress = new InetSocketAddress(port);
	}

	public UDPSocketControl64KBLimit(int port, InetAddress inet) throws SocketException 
	{
		super(port, inet);
		socketAddress = new InetSocketAddress(inet, port);
	}

	public UDPSocketControl64KBLimit(InetSocketAddress sa) throws SocketException 
	{
		super(sa);
		socketAddress = sa;
	}


	public void sendData(Object data) throws IOException 
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);

		oos.writeObject(data);
		byte[] buff = baos.toByteArray();

		DatagramPacket dp = new DatagramPacket(buff, buff.length, socketAddress);
		this.send(dp);
	}
	public void sendData(Object data,InetAddress inet) throws IOException 
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);

		oos.writeObject(data);
		byte[] buff = baos.toByteArray();


		DatagramPacket dp = new DatagramPacket(buff, buff.length,inet ,socketAddress.getPort());
		this.send(dp);
	}



	public void startListen()
	{
		runListen = true;
		Thread t = new Thread(this);
		t.start();
	}

	public void stopListen()
	{
		runListen = false;
	}

	public void run() 
	{


		synchronized (reciveData) 
		{
			byte[] buff = new byte[ 64 * 1024 ];
			DatagramPacket dp = new DatagramPacket(buff, buff.length);
			while(runListen)
			{
				try 
				{
					this.receive(dp);
					ByteArrayInputStream bais = new ByteArrayInputStream(dp.getData(),0,dp.getLength());
					ObjectInputStream ois = new ObjectInputStream(bais);
					
					
					reciveData.offer(ois.readObject());
					
				} catch (IOException e) 
				{
					e.printStackTrace();
					continue;
				} catch (ClassNotFoundException e) 
				{
					e.printStackTrace();
					continue;
				}
			}
		}

	}


}
